<template>
	<view class="edit-category-page">
		<uni-section title="修改分类" type="line" class="section-header">
			<view class="form-container">
				<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData" class="category-form">
					<uni-forms-item label-width="180rpx" label="分类名称" required name="name">
						<uni-easyinput v-model="valiFormData.name" placeholder="请输入分类名称" class="form-input"
							placeholderStyle="color: #a0b1c5;" />
					</uni-forms-item>

					<uni-forms-item label-width="180rpx" label="描述" name="description">
						<uni-easyinput v-model="valiFormData.description" placeholder="请输入分类描述" class="form-input"
							placeholderStyle="color: #a0b1c5;" />
					</uni-forms-item>

					<uni-forms-item label-width="180rpx" label="排序" required name="sort">
						<uni-easyinput v-model.number="valiFormData.sort" placeholder="数字越大排序越靠后" class="form-input"
							placeholderStyle="color: #a0b1c5;" />
						<view class="hint-text">注：请输入0或正整数</view>
					</uni-forms-item>

					<uni-forms-item label-width="180rpx" label="创建时间" name="create_date">
						<uni-easyinput v-model="valiFormData.create_date" disabled class="disabled-input" />
					</uni-forms-item>

					<view class="form-buttons">
						<button type="default" class="cancel-button" @click="goBack">返回</button>
						<button type="primary" class="submit-button" @click="submit('valiForm')">保存修改</button>
					</view>

					<button @click="deleteCategory" type="warn" class="delete-button">
						<uni-icons type="trash" size="18" color="#fff"></uni-icons>
						删除分类
					</button>
				</uni-forms>
			</view>
		</uni-section>

		<view class="decorative-element"></view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				id: null,
				valiFormData: {
					name: '',
					sort: null,
					description: '',
					create_date: null
				},
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '名称不能为空'
						}]
					},
					sort: {
						rules: [{
							required: true,
							errorMessage: '排序不能为空'
						}, {
							format: 'number',
							validate: (rule, value) => {
								// 自定义验证确保输入的是非负数字
								return Number(value) >= 0;
							},
							errorMessage: '只能输入非负数字'
						}]
					}
				}
			}
		},
		onLoad() {
			//console.log(uni.$router.params, 'params')
			if (uni.$router.params?._id) {
				this.id = uni.$router.params._id
				this.getCategoryDetail();
			} else {
				uni.showToast({
					title: '缺少分类ID',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},
			async getCategoryDetail() {
				try {
					const obj = uniCloud.importObject('goods');
					const res = await obj.getCategoriesList({
						_id: this.id
					});

					if (res.code === 0 && res.data.length > 0) {
						const category = res.data[0];
						this.valiFormData = {
							name: category.name,
							sort: category.sort,
							description: category.description || '',
							create_date: this.formatDate(category.create_date)
						};
					} else {
						uni.showToast({
							title: '获取分类详情失败',
							icon: 'none'
						});
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					}
				} catch (err) {
					uni.showToast({
						title: '获取详情失败',
						icon: 'none'
					});
					//console.error('获取分类详情错误:', err);
				}
			},

			async submit(ref) {
				try {
					// 表单验证
					await this.$refs[ref].validate();

					// 构造更新数据
					const updateData = {
						name: this.valiFormData.name,
						sort: this.valiFormData.sort,
						description: this.valiFormData.description
					};

					// 调用云对象更新接口
					const obj = uniCloud.importObject('goods');
					const res = await obj.updateCategory(this.id, updateData);

					if (res.code === 0) {
						uni.showToast({
							title: '更新成功',
							icon: 'success'
						});

						// 返回上一页
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none'
						});
					}
				} catch (err) {
					uni.showToast({
						title: '提交失败，请重试',
						icon: 'none'
					});
					//console.error('表单提交错误:', err);
				}
			},

			async deleteCategory() {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除该分类吗？此操作不可恢复',
					success: async (res) => {
						if (res.confirm) {
							try {
								const obj = uniCloud.importObject('goods');
								const result = await obj.updateCategory(this.id, {
									status: 1
								});

								if (result.code === 0) {
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									});

									// 返回上一页
									setTimeout(() => {
										uni.$router.to({
											url: '/pagesA/item/categories/list',
										})
									}, 1500);
								} else {
									uni.showToast({
										title: result.message,
										icon: 'none'
									});
								}
							} catch (err) {
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								});
								//console.error('删除分类错误:', err);
							}
						}
					}
				});
			},

			// 日期格式化
			formatDate(timestamp) {
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}`;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.edit-category-page {
		background: linear-gradient(135deg, #e6f0ff 0%, #f0f7ff 100%);
		min-height: 100vh;
		padding: 20rpx;
		position: relative;
		overflow: hidden;
	}

	.section-header {
		background: #fff;
		border-radius: 20rpx;
		overflow: hidden;
		box-shadow: 0 8rpx 30rpx rgba(26, 115, 232, 0.1);
		margin-bottom: 30rpx;
		border: 1rpx solid #d0e3ff;
	}

	.form-container {
		padding: 30rpx;
		background: #fff;
		border-radius: 20rpx;
	}

	.category-form {
		padding: 20rpx;
	}

	.form-input {
		background: #f9fbfe;
		border-radius: 16rpx;
		border: 1rpx solid #d0e3ff;
		padding: 18rpx 25rpx;
		font-size: 28rpx;
		color: #2c3e50;
		transition: all 0.3s;
	}

	.disabled-input {
		background: #f5f9ff !important;
		border: 1rpx solid #d0e3ff !important;
		color: #5a7ea0 !important;
		border-radius: 16rpx;
		padding: 18rpx 25rpx;
	}

	.form-input:focus {
		border-color: #1a73e8;
		box-shadow: 0 0 0 4rpx rgba(26, 115, 232, 0.15);
	}

	.hint-text {
		font-size: 24rpx;
		color: #5a7ea0;
		margin-top: 10rpx;
		padding-left: 10rpx;
	}

	.form-buttons {
		display: flex;
		justify-content: center;
		margin-top: 40rpx;
		margin-bottom: 20rpx;
		gap: 30rpx;
	}

	.cancel-button {
		width: 200rpx;
		height: 80rpx;
		line-height: 80rpx;
		background: #f0f7ff;
		color: #1a73e8;
		border: 1rpx solid #1a73e8;
		border-radius: 50rpx;
		font-size: 30rpx;
		font-weight: bold;
		transition: all 0.3s;
	}

	.cancel-button:active {
		background: #e1ecff;
		transform: translateY(4rpx);
	}

	.submit-button {
		width: 200rpx;
		height: 80rpx;
		line-height: 80rpx;
		background: linear-gradient(90deg, #1a73e8, #4d9aff);
		color: #fff;
		border-radius: 50rpx;
		font-size: 30rpx;
		font-weight: bold;
		box-shadow: 0 8rpx 20rpx rgba(26, 115, 232, 0.3);
		transition: all 0.3s;
	}

	.submit-button:active {
		transform: translateY(4rpx);
		box-shadow: 0 4rpx 10rpx rgba(26, 115, 232, 0.3);
	}

	.delete-button {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		background: linear-gradient(90deg, #ff5252, #ff7b7b);
		color: #fff;
		border-radius: 50rpx;
		font-size: 32rpx;
		font-weight: bold;
		margin-top: 30rpx;
		box-shadow: 0 8rpx 20rpx rgba(255, 82, 82, 0.25);
		display: flex;
		justify-content: center;
		align-items: center;
		gap: 10rpx;
		transition: all 0.3s;
	}

	.delete-button:active {
		transform: translateY(4rpx);
		box-shadow: 0 4rpx 10rpx rgba(255, 82, 82, 0.25);
	}

	.decorative-element {
		position: absolute;
		bottom: -100rpx;
		right: -100rpx;
		width: 300rpx;
		height: 300rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, rgba(26, 115, 232, 0.1) 0%, rgba(77, 154, 255, 0.05) 100%);
		z-index: 0;
	}

	::v-deep .uni-forms-item__label {
		font-weight: bold;
		color: #1a4e8e !important;
		font-size: 30rpx;
	}

	::v-deep .uni-forms-item__content {
		margin-bottom: 30rpx;
	}
</style>